package net.qhzw.geologr5.gis.service.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.qhzw.geologr5.gis.api.system.entity.User;
import net.qhzw.geologr5.gis.common.framework.utils.JsonResult;
import net.qhzw.geologr5.gis.common.framework.utils.StringUtils;
import net.qhzw.geologr5.gis.common.security.utils.SecurityUtils;
import net.qhzw.geologr5.gis.service.system.dto.BorrowDto;
import net.qhzw.geologr5.gis.service.system.entity.BorrowDetails;
import net.qhzw.geologr5.gis.service.system.entity.GisCart;
import net.qhzw.geologr5.gis.service.system.entity.ProjectData;
import net.qhzw.geologr5.gis.service.system.entity.ProjectMap;
import net.qhzw.geologr5.gis.service.system.mapper.*;
import net.qhzw.geologr5.gis.service.system.model.GisCartParam;
import net.qhzw.geologr5.gis.service.system.model.GisCartPo1;
import net.qhzw.geologr5.gis.service.system.model.GisCartPo2;
import net.qhzw.geologr5.gis.service.system.pojo.CartVo;
import net.qhzw.geologr5.gis.service.system.pojo.ProjectDataCartVo;
import net.qhzw.geologr5.gis.service.system.pojo.ProjectMapCartVo;
import net.qhzw.geologr5.gis.service.system.query.GisCartQuery;
import net.qhzw.geologr5.gis.service.system.service.GisCartService;
import net.qhzw.geologr5.gis.service.system.utils.StringUtil;
import net.qhzw.geologr5.gis.service.system.utils.UUIDUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class GisCartServiceImpl implements GisCartService {


    @Autowired
    private GisCartMapper gisCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProjectDataMapper projectDataMapper;

    @Autowired
    private ProjectMapMapper projectMapMapper;

    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private BorrowDetailsMapper borrowDetailsMapper;

    @Value("${file.projectDate.accsPathPrfx}")
    private String accsPathPrfx;


    /***
     * 添加购物车
     * @param param
     * @return
     */
    @Override
    public JsonResult add(GisCartParam param) {
        Integer userId = SecurityUtils.getLoginUser().getUserId();
        User user = userMapper.selectById(userId);
        if (user == null) {
            return JsonResult.error("获取不到当前用户");
        }
        //购物车原有的数据
        List<Integer> mapIdLists = new ArrayList<>();
        List<Integer> projectDataIds = new ArrayList<>();
        List<GisCart> gisCartList = gisCartMapper.selectGisCartByUserId(userId);
        for (GisCart gisCart : gisCartList) {
            if (gisCart.getMapId() != null && gisCart.getMapId() > 0) {
                mapIdLists.add(gisCart.getMapId());
            }
            if (gisCart.getProjectDataId() != null && gisCart.getProjectDataId() > 0) {
                projectDataIds.add(gisCart.getProjectDataId());
            }
        }
        List<GisCart> cartList1 = new ArrayList<>();
        List<GisCart> cartList2 = new ArrayList<>();
        //添加的数据
        if (param.getMapId() != null && param.getMapId().length > 0){
            Integer[] mapId = param.getMapId();
            List<Integer> integers = Arrays.asList(mapId);
            List<Integer> nodup = this.nodup(mapIdLists, integers);
            //添加地图资料 到购物车
            for (Integer integer : nodup) {
                GisCart cart = new GisCart();
                cart.setId(UUIDUtil.getUUid());
                cart.setUserId(userId);
                cart.setMapId(integer);
                cart.setCreateTime(new Date());
                cartList1.add(cart);
            }
        }
        //添加项目资料到 购物车
        if (param.getProjectDataId() != null && param.getProjectDataId().length > 0){
            Integer[] mapId = param.getProjectDataId();
            List<Integer> integers = Arrays.asList(mapId);
            List<Integer> nodup = this.nodup(projectDataIds, integers);
            for (Integer integer : nodup) {
                GisCart cart = new GisCart();
                cart.setId(UUIDUtil.getUUid());
                cart.setUserId(userId);
                cart.setProjectDataId(integer);
                cart.setCreateTime(new Date());
                cartList2.add(cart);
            }

        }
        //保存购物车数据
        if (cartList1 != null && !cartList1.isEmpty()) {
            gisCartMapper.insertBatch(cartList1);
        }
        if (cartList2 != null && !cartList2.isEmpty()) {
            gisCartMapper.insertBatch(cartList2);
        }
        return JsonResult.success();
    }

    @Override
    public JsonResult index(GisCartParam param) {
        //PageHelper.startPage(param.getPage(), param.getLimit());
        Map<String, Object> result = new HashMap<>();
        Integer userId = SecurityUtils.getLoginUser().getUserId();
        User user = userMapper.selectById(userId);
        if (user == null) {
            return JsonResult.error("获取不到当前用户");
        }
        GisCartQuery query = new GisCartQuery();
        query.setUserId(userId);
        //计算分页
        query.setPage((param.getPage() -1) * param.getLimit());
        query.setLimit(param.getLimit());
        if (param.getFlag() != null && !StringUtils.isEmpty(param.getFlag())){
            query.setFlag(param.getFlag());
        }
        List<CartVo> cartVoList = gisCartMapper.selectCartList(query);
        int total = gisCartMapper.selectCartTotal(query);
        for (CartVo cartVo : cartVoList) {
            if (cartVo.getType() != null && !StringUtils.isEmpty(cartVo.getType()) && "1".equals(cartVo.getType())) {
                if (cartVo.getFileUrl() != null && !StringUtils.isEmpty(cartVo.getFileUrl())) {
                    cartVo.setFileUrl(accsPathPrfx + cartVo.getFileUrl());
                }
            }
        }
        result.put("total", total);
        result.put("list", cartVoList);
        PageInfo<CartVo> pageInfo = new PageInfo<>(cartVoList);
        return JsonResult.success(result);

    }

    /***
     * 删除购物车
     * @param param
     * @return
     */
    @Override
    public JsonResult delete(GisCartParam param) {
        String id = param.getCartId();
        if (id == null && id.length() <= 0) {
            return JsonResult.error("请选择一个删除");
        }
        String[] split = id.split(",");
        List<String> list = Arrays.asList(split);
        gisCartMapper.deleteByPrimaryKey(list);
        return JsonResult.success();
    }

    /***
     * 去重复数据
     * @return
     */
    private List<Integer> nodup(List<Integer> list, List<Integer> list2) {
        if (list == null || list.isEmpty()){
            return list2;
        }
        List<Integer> result = new ArrayList<>();
        for (Integer integer : list2) {
            if (!list.contains(integer)) {
                result.add(integer);
            }
        }
        return result;
    }

    /***
     * 申请资源
     * @param param
     * @return
     */
    @Override
    public JsonResult reqResources(GisCartParam param) {
        if (param.getCartId() == null && param.getCartId().length() <= 0) {
            return JsonResult.error("购物车id null");
        }
        String[] split = param.getCartId().split(",");
        List<String> list = Arrays.asList(split);
        List<GisCart> gisCartList = gisCartMapper.selectListByIdIn(list);

        List<Integer> mapId = new ArrayList<>();
        List<Integer> projectDataId = new ArrayList<>();
        for (GisCart gisCart : gisCartList) {
            if (gisCart.getMapId() != null && gisCart.getMapId() >= 0) {
                mapId.add(gisCart.getMapId());
            }
            if (gisCart.getProjectDataId() != null && gisCart.getProjectDataId() >= 0) {
                projectDataId.add(gisCart.getProjectDataId());
            }
        }

        List<ProjectData> projectDataList = new ArrayList<>();
        if (projectDataId != null && !projectDataId.isEmpty()) {
            projectDataList = projectDataMapper.selectByIdList(projectDataId);
        }
        List<ProjectMap> projectMapList = new ArrayList<>();
        if (mapId != null && !mapId.isEmpty()) {
            projectMapList = projectMapMapper.selectByIdList(mapId);
        }

        //获取当前登录的用户id
        Integer userId = SecurityUtils.getLoginUser().getUserId();
        //日期格式流水号
        BorrowDto borrowDto = new BorrowDto();
        String uUid = UUIDUtil.getUUid();
        borrowDto.setId(uUid);
        borrowDto.setBorroTime(new Date());
        borrowDto.setDownloadCount(0);
        borrowDto.setUserId(userId);
        borrowDto.setOperation(0);
        borrowDto.setAudit(0);
        borrowDto.setBorroNo(getSerlNum());
        borrowMapper.insert(borrowDto);
        List<BorrowDetails> borrowDetailsList = new ArrayList<>();
        for (ProjectData projectData : projectDataList) {
            BorrowDetails borrowDetails = new BorrowDetails();
            borrowDetails.setFileId(projectData.getId());
            borrowDetails.setBorrowId(uUid);
            borrowDetails.setProjectId(projectData.getProjectId());
            borrowDetailsList.add(borrowDetails);

        }
        for (ProjectMap projectMap : projectMapList) {
            BorrowDetails borrowDetails = new BorrowDetails();
            borrowDetails.setMapId(projectMap.getId());
            borrowDetails.setBorrowId(uUid);
            borrowDetails.setProjectId(projectMap.getProjectId());
            borrowDetailsList.add(borrowDetails);
        }

        for (BorrowDetails borrowDetails : borrowDetailsList) {
            borrowDetailsMapper.insert(borrowDetails);
        }

        //删除购物车id
        gisCartMapper.deleteByPrimaryKey(list);

        return JsonResult.success();


    }


    /****
     * 返回流水号 serlNum
     *          2021081200200
     * @return
     */
    private String getSerlNum() {
        String serlNumMax = borrowMapper.selectSerlNumMax();
        String uid_pfix = getTimeStr();
        String max_code = serlNumMax;
        String comment_code = "";
        if (max_code != null && max_code.contains(uid_pfix)) {
            String uid_end = max_code.substring(8, max_code.length());
            //吧String类型00011 转化为int的1
            int endNum = Integer.parseInt(uid_end);
            //结果为100002
            int tmpNum = 100000 + endNum + 1;
            //把100002首为1去掉
            comment_code = uid_pfix + subStr("" + tmpNum, 1);
        } else {
            comment_code = uid_pfix + "00001";
        }
        return comment_code;
    }


    /***
     * 把100002的首尾1去掉的方法
     * @param str
     * @param start
     * @return
     */
    private String subStr(String str, int start) {
        if (str == null || str.equals("")) {
            return "";
        }
        if (start < str.length()) {
            return str.substring(start);
        } else {
            return "";
        }
    }

    private String getTimeStr() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date());
    }

    /***
     * 判断修改数据库返回值 返回
     * @param row
     * @param msg
     * @return
     */
    private JsonResult result(int row, String msg) {
        if (row > 0) {
            return JsonResult.success(null);
        }
        return JsonResult.error(msg);
    }


}
